package com.soyea.service;

import com.google.common.base.Preconditions;
import com.soyea.beans.PageQuery;
import com.soyea.beans.PageResult;
import com.soyea.common.OperateConstant;
import com.soyea.common.RequestHolder;
import com.soyea.dao.SysUserMapper;
import com.soyea.exception.ParamException;
import com.soyea.model.SysUser;
import com.soyea.param.UserParam;
import com.soyea.util.BeanValidator;
import com.soyea.util.IpUtil;
import com.soyea.util.MD5Util;
import com.soyea.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 系统用户管理
 * Created by skh on 2018/1/4
 */
@Service
@Transactional
public class SysUserService {

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private SysLogService sysLogService;

	/**
	 * 新增用户
	 *
	 * 思路:
	 * 校验参数
	 * 校验电话和邮箱是否被占用
	 * 随机生成密码,发送邮件给用户
	 * 将密码加密,数据库中的密码需要加密
	 * 填充用户属性
	 * 保存用户
	 * 保存日志
	 *
	 */
	public void save(UserParam param) {
		BeanValidator.check(param);
		if (checkTelephoneExist(param.getTelephone(), param.getId())) {
			throw new ParamException("电话已被占用");
		}
		if (checkEmailExist(param.getMail(), param.getId())) {
			throw new ParamException("邮箱已被占用");
		}
		String password = PasswordUtil.randomPassword();
		//TODO:因为还没有发送邮件,所以先用默认的密码
		password = "123456";
		String encryptedPassword = MD5Util.encrypt(password);
		SysUser user = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
				.password(encryptedPassword).deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();

		user.setOperateIp(IpUtil.getUserIP(RequestHolder.getCurrentRequest()));
		user.setOperateTime(OperateConstant.operateTime);
		user.setOperator(RequestHolder.getCurrentUser().getUsername());

		// TODO: sendEmail 通过邮件通知用户注册成功,并告知密码

		sysUserMapper.insertSelective(user);
		sysLogService.saveUserLog(null, user);
	}

	/**
	 * 修改用户
	 *
	 * 思路:
	 * 校验参数
	 * 校验电话和邮箱是否被占用
	 * 根据id,获取该用户
	 * 修改用户属性
	 * 更新用户
	 * 保存日志
	 * @param param
	 */
	public void update(UserParam param) {
		BeanValidator.check(param);
		if(checkTelephoneExist(param.getTelephone(), param.getId())) {
			throw new ParamException("电话已被占用");
		}
		if(checkEmailExist(param.getMail(), param.getId())) {
			throw new ParamException("邮箱已被占用");
		}
		SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
		Preconditions.checkNotNull(before, "待更新的用户不存在",param.getId());
		SysUser after = SysUser.builder().id(param.getId()).username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
				.deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();

		after.setOperateIp(IpUtil.getUserIP(RequestHolder.getCurrentRequest()));
		after.setOperateTime(OperateConstant.operateTime);
		after.setOperator(RequestHolder.getCurrentUser().getUsername());
		sysUserMapper.updateByPrimaryKeySelective(after);
		sysLogService.saveUserLog(before, after);
	}

	public boolean checkEmailExist(String mail, Integer userId) {
		return sysUserMapper.countByMail(mail, userId) > 0;
	}

	public boolean checkTelephoneExist(String telephone, Integer userId) {
		return sysUserMapper.countByTelephone(telephone, userId) > 0;
	}

	public SysUser findByKeyword(String keyword) {
		return sysUserMapper.findByKeyword(keyword);
	}

	/**
	 * 分页查询指定部门下的用户列表
	 *
	 * 思路:
	 * 查询指定部门下的用户数量
	 * 如果用户数量大于>0,再查询用户列表,返回总数和用户列表
	 * 实际可以用pagehelper
	 *
	 * @param deptId
	 * @param page
	 * @return
	 */
	public PageResult<SysUser> getPageByDeptId(int deptId, PageQuery page) {
		BeanValidator.check(page);
		//查询指定部门下的用户列表
		int count = sysUserMapper.countByDeptId(deptId);
		if (count > 0) {
			//分页查询用户列表
			List<SysUser> list = sysUserMapper.getPageByDeptId(deptId, page);
			return PageResult.<SysUser>builder().total(count).data(list).build();
		}
		return PageResult.<SysUser>builder().build();
	}

	/**
	 * 查询所有用户
	 * @return
	 */
	public List<SysUser> getAll() {
		return sysUserMapper.getAll();
	}
}
